package com.chushouya.common.applet;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.chushouya.common.enums.RedisKeys;
import com.chushouya.common.enums.RedisLocks;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Jsons;
import com.general.framework.core.lang.Numbers;
import com.general.framework.core.lang.Strings;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DouyinClient {

    private static String appid = "";
    private static String secret = "";
    private static String accessToken = "";

//    private final Client client;
    /**
     * 抖音客户端
     */
    public DouyinClient(String appid, String secret) {
//        this.appid = appid;
//        this.secret = secret;
//        Config config = new Config().setClientKey(appid).setClientSecret(secret);
//        try {
//            client = new Client(config);
//        } catch (Exception e) {
//            throw Ex.business("抖音客户端初始化失败");
//        }
    }

    /**
     * 获取抖音access_token
     */
    public String getDouyinAccessToken(String appid,String secret) {
        final String accessTokenRedisKey = Strings.format(RedisKeys.ACCESS_TOKEN, appid);
        if (RedisHolder.REDIS_CACHE.exist(accessTokenRedisKey)) {
            return RedisHolder.REDIS_CACHE.getCacheObject(accessTokenRedisKey);
        }

        //不存在获取最新
        RLock lock = RedisHolder.REDISSON_CLIENT.getLock(Strings.format(RedisLocks.ACCESS_TOKEN_LOCK, appid));
        try {
            //获取锁超时
            if (!lock.tryLock(5, TimeUnit.SECONDS)) {
                throw Ex.business("服务繁忙, 请稍后重试");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        try {
            if (RedisHolder.REDIS_CACHE.exist(accessTokenRedisKey)) {
                return RedisHolder.REDIS_CACHE.getCacheObject(accessTokenRedisKey);
            }

            JSONObject json = requestAccessToken();
            if (json == null) {
                throw Ex.business("获取accessToken异常");
            }
            log.info("抖音获取accessToken:{}", json);
            String accessToken = json.getJSONObject("data").getString("access_token");
            if (Strings.isBlank(accessToken)) {
                throw Ex.business(json.containsKey("err_tips") ? json.getString("err_tips") : "获取accessToken异常");
            }
            RedisHolder.REDIS_CACHE.setCacheObject(accessTokenRedisKey, accessToken, json.getJSONObject("data").getLongValue("expires_in"), TimeUnit.SECONDS);
            return accessToken;
        } finally {
            lock.unlock();
        }
    }

    /**
     * 从抖音获取最新的accessToken
     */
    public JSONObject requestAccessToken() {

        Map<String, Object> map = new HashMap<>();
        map.put("grant_type", "client_credential");
        map.put("appid", appid);
        map.put("secret", secret);

        String url = "https://developer.toutiao.com/api/apps/v2/token";
        String resp = HttpUtil.post(url, Jsons.toJsonString(map));
        log.debug("从抖音获取最新的accessToken响应:{}", resp);
        JSONObject json = Jsons.parseObject(resp);
        if (!Objects.equals(json.getInteger("err_no"), Numbers.INTEGER_ZERO)) {
            log.info("抖音获取accessToken异常: {}", resp);
            throw Ex.business(json.getString("err_tips"));
        }
        return json;
    }

    /**
     * 查询抖音券信息
     */
//    public GetCouponReceiveInfoResponse queryCouponMeta(String couponId, String openId) {
//        GetCouponReceiveInfoRequest sdkRequest = new GetCouponReceiveInfoRequest();
//        final String accessToken = this.accessToken = this.getDouyinAccessToken(appid, secret);
//        log.info("抖音券信息查询:{}", accessToken);
//        sdkRequest.setAccessToken(accessToken);
//        sdkRequest.setAppId(this.appid);
//        sdkRequest.setCouponId(couponId);
//        sdkRequest.setCouponStatus(10);
//        sdkRequest.setOpenId(openId);
//        GetCouponReceiveInfoResponse sdkResponse = null;
//        try {
//            sdkResponse = client.GetCouponReceiveInfo(sdkRequest);
//            log.info("抖音券信息查询:{}", Jsons.toJsonString(sdkRequest));
//            log.info("抖音券信息查询结果:{}", Jsons.toJsonString(sdkResponse));
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//        return sdkResponse;
//    }
}
